package com.gogowan.agroenterprise.newview;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Debug;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.contorl.RetrofitUtil.GsonUtil;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.NewBoxCode;
import com.gogowan.agroenterprise.model.NewOutStorageBoxResult;
import com.gogowan.agroenterprise.model.OutBackRequest;
import com.gogowan.agroenterprise.model.OutCheckRequest;
import com.gogowan.agroenterprise.model.OutStorageRequest;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.DialogUitl;
import com.gogowan.agroenterprise.utils.INewAdapterClick;
import com.gogowan.agroenterprise.utils.ListDataSave;
import com.gogowan.agroenterprise.utils.NetWorkManger;
import com.gogowan.agroenterprise.utils.ToastUtils;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.adapter.Base_Adapater;
import com.gogowan.agroenterprise.widget.adapter.HwScanAdapter;
import com.gogowan.agroenterprise.widget.adapter.MyBaseAdapater;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OutStorageReturnActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.out_storage_fh_btn)
    ImageButton outStorageFhBtn;
    @BindView(R.id.out_storage_smhqdh_btn)
    ImageView outStorageSmhqdhBtn;
    @BindView(R.id.out_storage_ckmc_text)
    TextView outStorageCkmcText;
    @BindView(R.id.out_storage_jxs_spinner)
    Spinner outStorageJxsSpinner;
    @BindView(R.id.xssj)
    Button xssj;
    @BindView(R.id.out_storage_smrkxm_btn)
    Button outStorageSmrkxmBtn;
    @BindView(R.id.out_storage_smrkxm_btn_hw)
    Button outStorageSmrkxmBtnHw;
    @BindView(R.id.out_storage_xmlist)
    ListView outStorageXmlist;
    @BindView(R.id.out_storage_qrck_btn)
    Button outStorageQrckBtn;
    @BindView(R.id.code_count_Tv)
    TextView codeCountTv;
    @BindView(R.id.btn_clear)
    Button btn_clear;

    private TextView outStorageDhEdit;
    private String OldeOrderCode = "";
    private ProgressDialog progressDialog;
    private List<NewBoxCode> BoxInfo = new ArrayList<>();
    private List<String> codes = new ArrayList<>();
    private HwScanAdapter adapater;
    private ListDataSave<String> dataSave;
    private boolean isHeadBack=true;
    private long userId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_activity_out_storage_return);
        ButterKnife.bind(this);
        userId=MyApplication.mSettings.getLong("personid",0);
        dataSave=new ListDataSave<>();
        TextView title = (TextView) findViewById(R.id.out_activity_title_tv);
        title.setText("出库退返");
        findViewById(R.id.out_storage_fh_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isHeadBack=true;
                finish();
            }
        });
        findViewById(R.id.btn_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(codes.size()<=0){
                    Toast.makeText(OutStorageReturnActivity.this,"请先扫码",Toast.LENGTH_LONG).show();
                    return;
                }
               DialogUitl.showTongyongSubmitDailog(OutStorageReturnActivity.this, "提示","您确定清空"+codes.size()+"条扫码记录嘛？", new DialogUitl.DialogClickCallBack() {
                   @Override
                   public void okButtonClick() {
                       codes.clear();
                       codeCountTv.setText(codes.size()+"");
                       adapater.notifyDataSetChanged();
                       dataSave.setDataList(userId+MyApplication.NEW_OUT_STORAGE_RETURN,new ArrayList<String>());
                   }

                   @Override
                   public void cancleButtonClick() {

                   }
               });

            }
        });
        adapater = new HwScanAdapter(this, codes, new INewAdapterClick() {
            @Override
            public void onItemClick(View view, int position) {
                showWindow(position);
            }
        });

        outStorageXmlist.setAdapter(adapater);
        outStorageDhEdit = (TextView) findViewById(R.id.out_storage_dh_edit);
        outStorageDhEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText editText = new EditText(OutStorageReturnActivity.this);
                new AlertDialog.Builder(OutStorageReturnActivity.this)
                        .setTitle("请输入单号")
                        .setView(editText)
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EditOrder(editText.getText().toString());
                                BoxInfo.clear();
                                codeCountTv.setText(codes.size()+"");
                                adapater.notifyDataSetChanged();
                            }
                        })
                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .show();
            }
        });
        outStorageSmhqdhBtn.setOnClickListener(this);
        outStorageSmrkxmBtn.setOnClickListener(this);
        outStorageSmrkxmBtnHw.setOnClickListener(this);
//        outStorageSmrkxmBtnHw.setVisibility(View.GONE);
        outStorageQrckBtn.setOnClickListener(this);
        List<String> dataList = dataSave.getDataList(userId+MyApplication.NEW_OUT_STORAGE_RETURN);
        if(dataList!=null&&dataList.size()>0){
            codes.addAll(dataList);
            codeCountTv.setText(codes.size() + "");
        }
        if(Debug.isDebuggerConnected()){
            codes.add(0,"MA.156.M0.100366.1c031501.S0168.M230329.L20230301.V260328.C3");
            codeCountTv.setText(codes.size()+"");
        }
    }

    private void showWindow(final int position) {
        DialogUitl.showDeleteDailog(
                this,
                codes.get(position),
                (codes.size() - position) + "", new DialogUitl.DialogClickCallBack() {
                    @Override
                    public void okButtonClick() {
                        codes.remove(position);
                        codeCountTv.setText(codes.size()+"");
                        adapater.notifyDataSetChanged();
                    }

                    @Override
                    public void cancleButtonClick() {

                    }
                });


//        new AlertDialog.Builder(this)
//                .setTitle("提示")
//                .setMessage("您是否要删除此条数据")
//                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
////                        BoxInfo.remove(position);
//                        codes.remove(position);
//                        adapater.notifyDataSetChanged();
//                        codeCountTv.setText(codes.size()+"");
//                    }
//                })
//                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                })
//                .show();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.out_storage_smhqdh_btn:
                // 扫码获取单号
                intent = new Intent(Intents.Scan.ACTION);
                this.startActivityForResult(intent, 10);
                break;
            case R.id.out_storage_smrkxm_btn:
                // 扫描入库箱码
//                intent = new Intent(Intents.Scan.ACTION);
//                intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
//                this.startActivityForResult(intent, 20);

                intent = new Intent(Intents.Scan.ACTION);
                intent.putExtra(Intents.Scan.IS_BULT_MODE, true);
                this.startActivityForResult(intent, 20);
                break;
            case R.id.out_storage_smrkxm_btn_hw:
                intent = new Intent(OutStorageReturnActivity.this, HWDialogActivity.class);
                intent.putExtra("type", "lx");
                intent.putExtra("codenumber", 1);
                this.startActivityForResult(intent, 505);
                break;
            case R.id.out_storage_qrck_btn:
                if (codes.size() < 1) {
                    showToast("请扫码!");
                    return;
                }
                boolean b = NetWorkManger.hasNet(getApplicationContext());
                if(b)
                    DialogUitl.showTishiDailog(OutStorageReturnActivity.this,
                            codes.size()+"",
                            new DialogUitl.DialogClickCallBack() {
                                @Override
                                public void okButtonClick() {
                                    SaveHttp();
                                }

                                @Override
                                public void cancleButtonClick() {

                                }
                            });
                else
                    ToastUtils.show(getApplicationContext(),"暂无网络");

                //TODO 换成好看的
//                new AlertDialog.Builder(OutStorageReturnActivity.this)
//                        .setTitle("提示")
//                        .setMessage("您是否确定要提交数据？")
//                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                SaveHttp();
//                            }
//                        })
//                        .setNeutralButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//
//                            }
//                        }).show();


                break;
        }
    }

    private void SaveHttp() {

//        if (outStorageDhEdit.getText().toString().length()<1&&MyApplication.mSettings.getInt("usertype",0)!=2){
//            showToast("请扫描单号！");
//            return;
//        }
        if (codes.size() < 1) {
            showToast("请扫码!");
            return;
        }
        progressDialog = ProgressDialog.show(this,
                getString(R.string.alert_title),
                "正在提交...", true, false);
        OutBackRequest outBackRequest = new OutBackRequest();
        outBackRequest.setBoxCode(codes);
        outBackRequest.setUserId(userId);
        OutStorageReturnAsyn outStorageAsyn = new OutStorageReturnAsyn();
        outStorageAsyn.execute(outBackRequest);
//        Http(outBackRequest, getString(R.string.addStorageReturnRecordApp),progressDialog, new RetrofitHttpListener() {
//            @Override
//            public void OnJson(String str) {
//                try {
//                    ResultInfo resultInfo = GsonUtil.GsonToBean(str, ResultInfo.class);
//                    if (resultInfo.getResult() >= 0) {
//                        showToast(resultInfo.getResultinfo());
//                        finish();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    showToast("解析失败！");
//                }
//            }
//        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String codeStr="";
            switch (requestCode) {
                case 10:
                    // 扫码获取单号
                    if (data!=null)
                        codeStr = data.getStringExtra(Intents.Scan.RESULT);
                    EditOrder(codeStr);
                    break;
                case 20:
                case 505:
                    // 扫描入库箱码
                    String s =   data.getStringExtra(Intents.Scan.RESULT);
                    List<String> codes = data.getStringArrayListExtra(Intents.Scan.RESULTLIST);

                    if (codes != null && codes.size() > 0) {
//                        s=codes.get(0);
                        for (int i = 0; i < codes.size(); i++) {
                            if(!codes.get(i).startsWith("MA.156.M0")){
                                codes.remove(i);
                                i--;
                                ToastUtils.show(getApplicationContext(),"存在无效码，已清除");
                            }
                        }
                        for (int i = 0; i < codes.size(); i++) {
                            String result = codes.get(i);
                            result=result.replaceAll("\n","");

                            String[] parts = result.split("MA.156.M0");
                            if (parts.length >= 3) {//"包含2个\"MA.156.M0\""
                                //
                                for (int j = 0; j < parts.length; j++) {
                                    if (j==1){
                                        if (!codes.contains("MA.156.M0"+parts[1])) {
                                            codes.set(i, "MA.156.M0" + parts[1]);
                                        }
                                    }else if(j>1){
                                        if (!codes.contains("MA.156.M0"+parts[j])) {
                                            codes.add(i + j + 1 - 2, "MA.156.M0" + parts[j]);
                                        }
                                    }
                                }
                            }
                        }
                        FindAgine(codes);
                    } else if (!Utils.isEmpty(s)) {
                        if(!s.startsWith("MA.156.M0")){
                            ToastUtils.show(getApplicationContext(),"存在无效码，已清除");
                            return;
                        }
                        FindAgine(s);
                    }else {
                        showToast("扫码失败!");
                    }
//                    if (Utils.isEmpty(s)) {
//
//                        return;
//                    }
//                    s = s.substring(s.indexOf("=") + 1, s.length());
//                    QueryHttp(s);
                    break;
                default:
                    break;
            }
        }
    }

    private void FindAgine(List<String> codes) {
        List<String>lists=new ArrayList<>();
        for (String val : codes) {
            if (!this.codes.contains(val)) {
                lists.add(val);
            }
        }
        this.codes.addAll(0,lists);
        codeCountTv.setText(this.codes.size()+"");
        adapater.notifyDataSetChanged();
    }

    private void FindAgine(String codes) {
        if (!this.codes.contains(codes)) {
            this.codes.add(0,codes);
        }
        adapater.notifyDataSetChanged();
        codeCountTv.setText(this.codes.size()+"");
    }

    private void EditOrder(final String codeStr) {
        if (OldeOrderCode.length() > 0 && (!OldeOrderCode.equals(codeStr))) {
            new AlertDialog.Builder(OutStorageReturnActivity.this)
                    .setTitle("提示")
                    .setMessage("更换单号将会清除已扫数据，您是否要更换单号")
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            outStorageDhEdit.setText(codeStr);
                            BoxInfo.clear();
                            codeCountTv.setText(codes.size()+"");
                            adapater.notifyDataSetChanged();
                        }
                    })
                    .setNeutralButton("否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .show();
        } else {
            outStorageDhEdit.setText(codeStr);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(isHeadBack){
            //如果手动退出需要加一个缓存把退库信息缓存到本地
            dataSave.setDataList(userId+MyApplication.NEW_OUT_STORAGE_RETURN,codes);
        }else{
            dataSave.setDataList(userId+MyApplication.NEW_OUT_STORAGE_RETURN,new ArrayList<String>());
        }
    }

    //    private void QueryHttp(String code) {
////        String OrderCode=outStorageDhEdit.getText().toString();
////        if (MyApplication.mSettings.getInt("usertype",0)!=2){
////            if (Utils.isEmpty(OrderCode)){
////                showToast("请扫描单号");
//////                return;
////            }else {
////                if (Utils.isEmpty(OrderCode)){
////                    OldeOrderCode=OrderCode;
////                }
////            }
////        }
//        progressDialog = ProgressDialog.show(this,
//                getString(R.string.alert_title),
//                getString(R.string.alert_message), true, false);
//        final OutCheckRequest outCheckRequest = new OutCheckRequest();
//        outCheckRequest.setScanEwm(code);
////        if (MyApplication.mSettings.getInt("usertype",0)!=2){
////            outCheckRequest.setOutStorageNO(OrderCode);
////        }
//        //outCheckRequest.setDealerId(loginResultInfo.getEnterpriseinfo().getDealerId());
//       // outCheckRequest.setEnterpriseId(loginResultInfo.getEnterpriseinfo().getEnterpriseid());
//        Http(outCheckRequest,"47000 : 191003", progressDialog, new RetrofitHttpListener() {
//            @Override
//            public void OnJson(String str) {
//                NewOutStorageBoxResult outStorageBoxResult = GsonUtil.GsonToBean(str, NewOutStorageBoxResult.class);
//                showToast(outStorageBoxResult.getResultinfo());
//                if (outStorageBoxResult != null) {
//                    if (outStorageBoxResult.getResult() > 0) {
//                        if (!Utils.isEmpty(outStorageBoxResult.getOutStorageNO() + "")) {
//                            outStorageDhEdit.setText(outStorageBoxResult.getOutStorageNO());
//                        }
//                        BoxInfo.addAll(outStorageBoxResult.getBoxInfo());
//                        adapater.notifyDataSetChanged();
//                    }
//                } else {
//                    showToast("数据解析失败！");
//                }
//            }
//        });
//    }
    /**
     * 确认出库请求
     *
     * @author tjh
     *
     */
    private class OutStorageReturnAsyn extends MyAsyncTask {

        @Override
        protected void onPostExecute(Object res) {
            progressDialog.dismiss();
            if (res == null || res.equals("")) {
                Toast.makeText(OutStorageReturnActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
            } else {
                try {
                    JSONObject jo=new JSONObject(res.toString());
                    Toast.makeText(getApplicationContext(),jo.getString("msg"),
                            Toast.LENGTH_LONG).show();
                    if(jo.getInt("code")!=200){
                        return;
                    }

                    isHeadBack=false;
                    OutStorageReturnActivity.this.finish();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            super.onPostExecute(res);
        }

        @Override
        protected Object doInBackground(Object... params) {
            OutBackRequest outStorageRequest = (OutBackRequest) params[0];

            String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.addStorageReturnRecordApp), outStorageRequest);
//            String res = Utils.getCommit(getString(R.string.first_url) + getString(R.string.addStorageReturnRecordApp)+
//                    "?codes="+outStorageRequest.getCodes()+"&personid="+outStorageRequest.getPersonid());
            return res;
        }
    }
}
